package com.demo.mybatis_plus.controller;

import com.demo.mybatis_plus.dto.ReservationParam;
import com.demo.mybatis_plus.dto.ApiResponse;
import com.demo.mybatis_plus.pojo.Reservation;
import com.demo.mybatis_plus.service.PetInfoService;
import com.demo.mybatis_plus.service.ReservationService;
import com.demo.mybatis_plus.service.UserinfoService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/reservation")
public class ReservationController {
    @Resource
    private ReservationService reservationService;
    @Resource
    private UserinfoService userinfoService;
    @Resource
    private PetInfoService petInfoService;

    @RequestMapping("/query")
    // 多条件查询
    public ApiResponse queryAll(@RequestBody ReservationParam reservationParam) {
        final List<Reservation> list = reservationService.getAll(reservationParam);
        return ApiResponse.success(list);
    }

    @PostMapping("/create")
    // springboot 中 requestBody默认类型为json
    public ApiResponse create(@RequestBody ReservationParam reservationParam) {
        // 应该验证参数的有效性
        if (!StringUtils.hasLength(reservationParam.getPhone())) {
//            throw new RuntimeException("参数不正确,请填写正确的手机号码");
            return ApiResponse.PARAM_ERROR;
        }
        // 名字 电话 宠物名称 品种 原因 时间
        final Reservation reservation
                = reservationService.create(reservationParam);
        // 统一响应结构
        return ApiResponse.success(reservation);
    }

    //验证预约信息
    @RequestMapping("/verify")
    public ApiResponse verify(Integer id, String phone) {
        // 验证参数 必须至少提供一个参数
        if(id == null && !StringUtils.hasLength(phone)){
            return ApiResponse.fail(1,"id和手机号码必须填写一个");
        }
        if(id != null && id < 1){
            return ApiResponse.PARAM_ERROR;
        }
        if (StringUtils.hasLength(phone) && !phone.matches("^\\d+$")) {
            return ApiResponse.PARAM_ERROR;
        }
        try {
            return ApiResponse.success(reservationService.verify(id, phone));
        } catch (Exception e) {
            return ApiResponse.fail(5000, e.getMessage());
        }
    }
}
